package com.learn.egmvc4.contorller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.learn.egmvc4.base.response.JsonResult;
import com.learn.egmvc4.mapper.UserMapper;
import com.learn.egmvc4.pojo.dto.UserAddParam;
import com.learn.egmvc4.pojo.dto.UserUpdateParam;
import com.learn.egmvc4.pojo.entity.User;
import com.learn.egmvc4.pojo.vo.UserListVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.List;

@Validated
@Api(tags = "01.用户管理模块")
@RestController
@Slf4j
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("add")
    @ApiOperation(value = "新增用户")
    @ApiOperationSupport(order = 10)
    public JsonResult AddUser(@Validated UserAddParam userAddParam){
//        System.out.println(userAddParam);
        log.debug("userAddParam:"+userAddParam);
        User user = new User();
        BeanUtils.copyProperties(userAddParam,user);
        user.setCreateTime(new Date());
        userMapper.insertUser(user);
        return JsonResult.ok();
    }

    @GetMapping("list")
    @ApiOperation(value = "用户列表")
    @ApiOperationSupport(order = 20)
    public JsonResult  userList(){
        List<UserListVO> userLIstVOS = userMapper.selectUserList();
        return JsonResult.ok(userLIstVOS);
    }

    @PostMapping("del")
    @ApiOperation(value = "删除用户")
    @ApiOperationSupport(order = 30)
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "int", paramType = "query")
    public JsonResult  deleteUser(@Range(min = 1,max = 100,message = "用户id必须在1-100之间") @RequestParam Integer id){
        if(id<0){
            throw new IllegalArgumentException("id不能小于0");
        }

        userMapper.deleteUser(id);
        return JsonResult.ok();
    }

    @PostMapping("update")
    @ApiOperation(value = "更新用户")
    @ApiOperationSupport(order = 40)
    public JsonResult  updateUser(@ApiIgnore UserUpdateParam userUpdateParam){
        User user = new User();
        BeanUtils.copyProperties(userUpdateParam,user);
        userMapper.userUpdate(user);
        return JsonResult.ok();
    }
}
